package View;


import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JButton;

import javax.swing.JLabel;
import javax.swing.JPanel;

import Presenter.SaveLoadPresenter;
import Model.Player;
import Model.SaveLoad.Trio;
/**
 * Class represents the load menu screen panel.
 */

public class LoadView extends JPanel {
	/**
	 * Instance of the GUI class which is responsible for the panels that the user sees.
	 */
	private final GUI gui = GUI.getInstance();

	/**
	 * A saveload presenter
	 */
	private final SaveLoadPresenter presenter;

	/**
	 * a list of groups of buttons, labels and strings
	 */
	private final List<Trio<JButton, JLabel, String>> loadGroups;

	/**
	 * button to go back to the load menu view
	 */
	private final JButton backButton;
	
	public LoadView(){
		presenter = new SaveLoadPresenter();
		loadGroups = new LinkedList<Trio<JButton, JLabel, String>>();
		backButton = new JButton("Back");
		int buttonNumber = 0;
		
		for(final String s: SaveLoadPresenter.FILE_NAMES){ // set the buttons and labels accordingly
			JLabel label;
			JButton button = new JButton("File" + buttonNumber);
			try {
				Player playerHere = presenter.getFileData(s);
				label = new JLabel("       " + "Name: " + playerHere.getName() + "; " 
				        + "Credits: " + playerHere.getCredits() + "; " + 
				        "Planet: " + playerHere.getCurrentPlanet().getName());
			} catch (ClassNotFoundException | IOException  | NullPointerException e) {
				label = new JLabel("NO DATA");
				button.setEnabled(false);
			}
			
			loadGroups.add(new Trio<JButton, JLabel, String>(button, label, s));
			
			button.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					new SaveLoadPresenter().loadGame(s);
					GUI.getInstance().setContentPane(new MainPageView(), 500, 430);
				}
			});
			buttonNumber++;
		}
		
		backButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				final GUI gui = GUI.getInstance();
				gui.setContentPane(new LoadMenuView(), 500, 400);
			}
		});
		
		this.setLayout(new GridLayout(7, 2));
		
		for(int i = 0; i < loadGroups.size(); i++){
			this.add(new JLabel(""));
			this.add(new JLabel(""));
			this.add(loadGroups.get(i).getA());
			this.add(loadGroups.get(i).getB());	
		}
		this.add(backButton);
		
	}

}
